package com.opensourceedge.phonebook.cli;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class PhoneBookCLI {

	ArrayList<Command> commandList;

	public PhoneBookCLI() {
		commandList = new ArrayList<Command>();
	}

	public ArrayList<Command> getCommandList() {
		return commandList;
	}

	public void addCommand(Command command) {
		this.commandList.add(command);
	}

	public static void main(String[] args) {

		PhoneBookCLI phonebook = new PhoneBookCLI();
		//
		AddContactCommand addContactCommand = new AddContactCommand();
		ModifyContactCommand modifyContactCommand = new ModifyContactCommand();
		DeleteContactCommand deleteContactCommand = new DeleteContactCommand();
		SearchContactCommand searchContactCommand = new SearchContactCommand();
		ExitCommand exitCommand= new ExitCommand();

		// add commands to phoneBook
		phonebook.addCommand(addContactCommand);
		phonebook.addCommand(modifyContactCommand);
		phonebook.addCommand(deleteContactCommand);
		phonebook.addCommand(searchContactCommand);
		phonebook.addCommand(exitCommand);

		// display help text for each command
		for (int i = 0; i < phonebook.commandList.size(); i++) {
			String helpText = phonebook.getCommandList().get(i)
					.getCommandHelpText();
			System.out.println(helpText);
		}

		//asks for command execute if matches else display error message.
		//Continuous loop.
		while (true) {
			// asks for input and will also display current value if available.
			System.out.print("\nEnter Command");
			System.out.print(" :");

			// gets input from command.
			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));
			try {
				String input = br.readLine();
				boolean isExecuted = false;

				for (int i = 0; i < phonebook.commandList.size(); i++) {
					// System.out.println("inside main loop");
					if (input.equalsIgnoreCase(phonebook.commandList.get(i)
							.getCommandCode())) {
						phonebook.commandList.get(i).execute();
						isExecuted = true;
						break;
					}
				}
				if (!isExecuted) {
					System.out
							.println("<<Error>> Invalid Command !!try again!!");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
